package com.sky.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.*;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AdminOrderMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.result.PageResult;
import com.sky.service.AdminOrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {
    @Autowired
    private AdminOrderMapper adminOrderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        // 根据条件查询Page<Orders>类型的集合数据
        Page<Orders> p = adminOrderMapper.page(ordersPageQueryDTO);

        // 根据查询的数据去获取OrderVO集合
        List<OrderVO> orderVOList = getOrderVOList(p);

        return new PageResult(p.getTotal(),orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> p) {
        // 创建一个空的OrderVO集合
        List<OrderVO> orderVOList = new ArrayList<>();
        // 获取查询的Orders返回的每条数据，集合ordersList
        List<Orders> ordersList = p.getResult();
        // 判断集合不为空
        if(ordersList != null && ordersList.size() > 0){
            // 遍历集合
            ordersList.forEach(orders -> {
                // 定义一个OrderVO对象
                OrderVO orderVO = new OrderVO();
                // 将orders拷贝到orderVO中
                BeanUtils.copyProperties(orders,orderVO);
                // 根据订单基本信息获取菜品信息
                String orderDishStr = getOrderDishStr(orders);
                // 将菜品信息存储到orderVO中的OrderDishes属性中
                orderVO.setOrderDishes(orderDishStr);
                // 将每条菜品信息存储到集合中
                orderVOList.add(orderVO);
            });
        }
        return orderVOList;
    }

    private String getOrderDishStr(Orders orders) {
        // 根据订单id获取订单详情信息集合
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        // 创建一个字符串集合用来接收菜品信息
        List<String> orderDishList = new ArrayList<>();
        // 遍历订单详情信息
        orderDetailList.forEach(orderDetail ->{
            // 将订单详情里面的菜品名称和份数进行拼接
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            // 将菜品信息字符串添加到orderDishList集合中
            orderDishList.add(orderDish);
        });
//        log.info("orderDishList数据：{}",orderDishList);
//        log.info("String.join(\"\",orderDishList)数据：{}",String.join("",orderDishList));

        return String.join("",orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 待接单数量
        Integer toBeConfiremed = orderDetailMapper.getStatus(Orders.TO_BE_CONFIRMED);
        // 待派送数量
        Integer confirmed = orderDetailMapper.getStatus(Orders.CONFIRMED);
        // 派送中数量
        Integer deliveryInProgress = orderDetailMapper.getStatus(Orders.DELIVERY_IN_PROGRESS);
        orderStatisticsVO.setToBeConfirmed(toBeConfiremed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        log.info("封装后的orderStatisticsVO：{}",orderStatisticsVO);
        return orderStatisticsVO;
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = adminOrderMapper.getById(id);
        BeanUtils.copyProperties(orders,orderVO,"id");
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
//        log.info("orderVO订单详情信息为：{}",orderVO);
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        adminOrderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        Orders adminOrders = adminOrderMapper.getById(ordersRejectionDTO.getId());
        if (adminOrders.getPayStatus().equals(Orders.PAID)){
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        adminOrderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        Orders cancelOrders = adminOrderMapper.getById(ordersCancelDTO.getId());
        if(cancelOrders.getPayStatus().equals(Orders.PAID)){
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
//        log.info("orders信息：{}",orders);
        adminOrderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
//        Orders deliveryOrders = adminOrderMapper.getById(id);
//        if(deliveryOrders.getStatus().equals(Orders.CONFIRMED)){
//
//        }
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        adminOrderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        adminOrderMapper.update(orders);
    }

}
